PATHMac OS 8 and 9 Developer Documentation > Interapplication Communication > AppleScript for Scripters >

AppleScript Language Guide

   

Creating Variables

To create a variable in AppleScript, assign it a value. There are two commands for doing this:

With the Set command, list the variable name first, followed by the value you want to assign:

set myName to "Paula"

With the Copy command, list the value first, followed by the variable name:

copy "Paula" to myName

Statements like these that assign values to variables are called assignment statements .

The variable name is a series of characters called an identifier. AppleScript identifiers are not case sensitive--for example, the variables myname , myName , and MYNAME all represent the same value. The rules for specifying identifiers are listed in Identifiers.

You can use an expression instead of a value in an assignment statement. AppleScript evaluates the expression and assigns the resulting value to the variable. For example, the following statement creates a variable called myNumber whose value is the integer 17.

set myNumber to 5 + 12

A variable can also get its value from a reference. In this case, AppleScript gets the value of the object specified in the reference and assigns it to the variable. For example, the following statement gets the value of the first word of the document called Report--a string--and stores it in a variable called myWord . The next three examples use the document shown in Figure 4-1 :

tell application "AppleWorks"
    set myWord to word 1 of text body of document "Simple"
end tell
--result: "This"

To create a variable whose value is the reference itself instead of the value of the object specified by a reference, use the A Reference To operator, which is described in more detail in The A Reference To Operator :

tell application "AppleWorks"
    set myWord to a reference to word 1 of text body of document "Simple"
end tell
--result:
-- word 1 of text body of document "Simple" of application "AppleWorks"

You can use the Copy command instead of the Set command to assign either a value or a reference to a variable. The following example assigns a value:

tell application "Finder"
    copy name of first file of startup disk to firstFileName
end tell
--result (depends on disk contents): "ASP Control Panel Report"

The results of the two types of assignment statements are the same in all cases except when the value being assigned is a list, record, or script object. The Copy command makes a new copy of the list, record, or script object, and the Set command creates a variable that shares data with the original list, record, or script object. For more information, refer to Data Sharing.


© 1999 Apple Computer, Inc. – (Last Updated 21 May 99)